
import { SerialPort ,ByteLengthParser } from 'serialport'
import{ sendmsg} from '../rabbitmq/rabbitmq.ts'
const fs = require("fs");
// const path = require('path');

let currentPort: SerialPort | null = null;
export { currentPort };



//获取串口列表
export const listSerialPorts = async () => {
  const ports = await SerialPort.list()

  if (ports.length === 0) {
    console.warn('No ports discovered')
    return [];
  } else {
    console.log('ports', ports);
    return ports;
  }
}

//打开串口
export const openSerialPort = async (ports: string, baudRate: number=9600) => {
  const port = new SerialPort({
    path: ports,
    baudRate: baudRate,
    autoOpen: false
  });
  const parser = port.pipe(new ByteLengthParser({ length:16 }));

  await new Promise((resolve, reject) => {
    port.open((err) => {
      if (err) return reject(err);
      console.log(`串口已打开: ${ports}`)
      currentPort = port;

      port.on('error', err => console.error('串口错误:', err));
      port.on('close', () => console.log('串口已关闭'));

      parser.on('data', (data:string) => {
        console.log(`串口数据: ${data}`);
        sendmsg(data);
      });

      resolve(port);
    });
  });
    
}
//关闭串口

export const closeSerialPort = async(port: SerialPort):Promise<void> => {
  return new Promise((resolve, reject) => {
    if (!port.isOpen){
      console.log('串口未打开');
      resolve();
      return
    }

    port.close((err) => {
      if (err){
        console.error('关闭串口失败:', err);
        reject(err);
      } else {
        console.log('串口已关闭');
        resolve();
          }
        });
      });
    }

export const closeCurrentPort = async (): Promise<void> => {
  if (!currentPort) {
    console.warn('没有可关闭的串口');
    return;
  }

  return closeSerialPort(currentPort);
};





//解析数据
export async function parseSerialData(experimentName:string){
  const fileName = `${experimentName}.txt`;
  const parsedfileName = `parsed_data_${experimentName}.txt`;
  const data =fs.readFileSync(fileName)

  const dataStr = data.toString().split("FFFF");//切割
  const results = [];
  
  for(let m = 1;  m < dataStr.length - 1; m++) {
    let j =0;
    for(let i = 4; i < dataStr[m].length; i+=4,j++) {
      const hexValue = dataStr[m].slice(i, i + 4);
      const intValue = parseInt(hexValue, 16);
      // 转换物理值
      const physicalValue = intValue * 0.0002426791781265167448632907296554;
      results.push(physicalValue);
      }
    }
    fs.writeFileSync(parsedfileName, results.join('\n'));
    console.log(`数据解析完成，结果已保存至${parsedfileName}`);
}





  
// export default {
//     listSerialPorts
// }



// Set a timeout that will check for new serialPorts every 2 seconds.
// This timeout reschedules itself.
